package com.yami.shop.mystery.common.listener;

import com.yami.shop.bean.event.OpenBoxSuccessEvent;
import com.yami.shop.mystery.common.dao.MysteryBoxOpenRecordMapper;
import com.yami.shop.mystery.common.model.MysteryBoxOpenRecord;
import com.yami.shop.service.SkuStockLockService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component("openBoxEventSuccessListener")
@AllArgsConstructor
public class OpenBoxEventSuccessListener {

    private final MysteryBoxOpenRecordMapper mysteryBoxOpenRecordMapper;

    private final SkuStockLockService skuStockLockService;

    @EventListener(OpenBoxSuccessEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void openBoxEventSuccessListener(OpenBoxSuccessEvent event) {
        // 更新开合记录状态为已完成2，补录tokenId信息
        MysteryBoxOpenRecord mysteryBoxOpenRecord = new MysteryBoxOpenRecord();
        mysteryBoxOpenRecord.setId(event.getMysteryBoxOpenRecordId());
        mysteryBoxOpenRecord.setStatus(2);
        mysteryBoxOpenRecord.setTokenId(event.getDawId());
        mysteryBoxOpenRecordMapper.updateById(mysteryBoxOpenRecord);
        // 减少盲盒中商品的锁定库存
        skuStockLockService.openBoxMarkerStockUse(event.getProdId(),1);
    }
}
